package com.hyzh.latte.vehicle.nezha;

import com.coffee.concurrent.CoffeeExecutorManager;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.RemovalListener;
import com.hyzh.latte.vehicle.dmo.VehicleBO;
import com.hyzh.latte.vehicle.dmo.VehicleDeleteMessage;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jetbrains.annotations.NotNull;

import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * @author: songkui
 * @since 2021-12-17
 */
@Slf4j
public class VehicleExpireHandler implements RemovalListener<String, VehicleBO> {
    @Override
    public void onRemoval(@Nullable String key, @Nullable VehicleBO value, @NotNull RemovalCause removalCause) {
        log.info("Vehicle expired: key:{}, value: {},  removalCause {}", key, null == value ? "value is null" : value.toString(),  removalCause);
        if (removalCause.equals(RemovalCause.EXPIRED)) {
            try {
                if (null != value) {
                    Set<NezhaClient> set = NezhaSessionManager.getInstance().setClientByParkCode(value.getParkCode());
                    String oid = value.getObjectId();
                    String vno = value.getVehicleNo();
                    CoffeeExecutorManager.getInstance().getSlowExecutor().execute(() -> {
                        for (NezhaClient client : set){
                            client.sendDeleteMsg(new VehicleDeleteMessage(oid, vno));
                        }
                    });
                    value = null;
                }
            } catch (Exception e) {
                log.error("Vehicle expired:key:  v: {};   {} ",   value, e.getMessage());
            }
        }
    }
}
